package top.milkbox.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import top.milkbox.domain.Click;
import top.milkbox.service.ClickService;
import top.milkbox.mapper.ClickMapper;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author xiaoguo
* @description 针对表【tb_click】的数据库操作Service实现
* @createDate 2022-04-28 18:07:47
*/
@Service
public class ClickServiceImpl extends ServiceImpl<ClickMapper, Click>
    implements ClickService{
    @Autowired
    private ClickMapper clickMapper;

    @Override
    public void addClick(Integer userinfoId, Integer menuId) {
        // 通过userinfoId和menuId查询是否存在记录
        QueryWrapper<Click> clickQueryWrapper = new QueryWrapper<>();
        clickQueryWrapper.eq("userinfo_id", userinfoId);
        clickQueryWrapper.eq("menu_simple_id", menuId);
        Click click = clickMapper.selectOne(clickQueryWrapper);
        if (click == null) {
            // 如果不存在记录，则新增一条记录
            Click newClick = new Click();
            newClick.setUserinfoId(userinfoId);
            newClick.setMenuSimpleId(menuId);
            newClick.setTimestemp(String.valueOf(new Date().getTime()));
            clickMapper.insert(newClick);
        } else {
            // 如果存在记录，点击数+1
            click.setClickCount(click.getClickCount() + 1);
            clickMapper.updateById(click);
        }

    }

    @Override
    public Integer getClickByMenuId(Integer menuId) {
        QueryWrapper<Click> wrapper = new QueryWrapper<>();
        wrapper.select("sum(click_count) as clickCount");
        wrapper.eq("menu_simple_id", menuId);

        // 注意，查询出来的Click对象中的clickCount只的是menuId对应的点击量之和
        Click clickOnlyClickCount = clickMapper.selectOne(wrapper);
        if (clickOnlyClickCount == null) {
            return 0;
        } else {
            return clickOnlyClickCount.getClickCount();
        }
    }
}




